package com.cory.module.msg.admin;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Value;
import com.cory.boot.component.cache.RedisUtils;
import com.cory.boot.utils.SysUtils;
import com.cory.module.msg.admin.annotation.AdminMsgSettings;
import com.cory.utils.lang.StringUtils;

/**
 * @author xiongcong
 * @date 2022-09-17
 */
public abstract class AdminMsg {
    
    @Value("${spring.application.name}:adminMsg:")
    private String REDIS_PREFIX;
    
    protected abstract long msgCount();
    
    public AdminMsgSettings settings() {
        return this.getClass().getAnnotation(AdminMsgSettings.class);
    }
    
    protected String key() {
        AdminMsgSettings settings = this.settings();
        String key = REDIS_PREFIX + settings.key();
        
        if ("user".equals(settings.type())) {
            key += "_" + SysUtils.getLoginUserId();
        }
        return key;
    }

    public long getMsg() {
        String val = RedisUtils.get(key());
        if (StringUtils.isNotBlank(val) && NumberUtils.isDigits(val)) {
            return Integer.valueOf(val);
        }
        return 0;
    }
    
    public void setMsg(long num) {
        RedisUtils.set(key(), num + "");
    }
    
    public void addMsg(long num) {
        setMsg(getMsg() + num);
    }

    public void reduceMsg(long num) {
        setMsg(getMsg() - num);
    }
    
    public void reloadMsg() {
        setMsg(msgCount());
    }
}
